package com.wibo.account;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.wibo.common.Utility;

import weibo4android.Weibo;
import weibo4android.WeiboException;
import weibo4android.http.AccessToken;
import weibo4android.http.RequestToken;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.Window;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;

public class WiboMainLoginActivity extends Activity {
	
	public static final String SETTINGS_TOKEN_PAIR = "TOKEN_PAIR";
	
	public static final String TOKEN = "token";
	public static final String TOKEN_SECRET = "tokenSecret";

	
	private String mToken = "";
	private String mTokenSecret = "";
	
	WebView mWebView;
	private static Weibo mWeibo = null;
	
	Thread mThread = null;
	
	private static ProgressDialog mWaitDialog = null;
	
	private static final int TURN_TO_OAUTH = 1;
	private static final int TURN_TO_MAIN = 2;
	private static final int GET_TOKEN = 3;
	
	Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			switch (msg.what) {
			case GET_TOKEN:
				Uri uri = Uri.parse((String)msg.obj);
				try {
					RequestToken requestToken = OAuthConstant.getInstance().getRequestToken();

					AccessToken accessToken = requestToken.getAccessToken(uri.getQueryParameter("oauth_verifier"));
					OAuthConstant.getInstance().setAccessToken(accessToken);
					
					SharedPreferences settings = getSharedPreferences(SETTINGS_TOKEN_PAIR, 0);
					Editor editor = settings.edit();
					editor.putString(TOKEN, OAuthConstant.getInstance().getToken());
					editor.putString(TOKEN_SECRET, OAuthConstant.getInstance().getTokenSecret());
					editor.commit();
					
					mWebView.clearCache(true);
                    mWebView.clearHistory();
                    mWebView.clearFormData();

                    mWebView.setVisibility(WebView.INVISIBLE);
					
					Intent intent = new Intent(WiboMainLoginActivity.this, WiboMainTabActivity.class);
					intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP );
					startActivity(intent);
                    finish();
//					TextView textView = (TextView) findViewById(R.id.TextView01);
//					textView.setText("得到AccessToken的key和Secret,可以使用这两个参数进行授权登录了.\n Access token:\n"+accessToken.getToken()+"\n Access token secret:\n"+accessToken.getTokenSecret());
				} catch (WeiboException e) {
					e.printStackTrace();
				}
				break;
				
			case TURN_TO_MAIN:
				Intent intent = new Intent(WiboMainLoginActivity.this, WiboMainTabActivity.class);
				intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP );
				startActivity(intent);
                finish();
				break;
			}
			super.handleMessage(msg);
		}
		
	};
	
	private void sendMessage(int what, Object obj) {

		Message msg = mHandler.obtainMessage(what, obj);
		mHandler.sendMessage(msg);
	}
	
    /** Called when the activity is first created. */
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

//        requestWindowFeature(Window.FEATURE_NO_TITLE);
//        setContentView(R.layout.main);
        
        System.setProperty("weibo4j.oauth.consumerKey", Weibo.CONSUMER_KEY);
    	System.setProperty("weibo4j.oauth.consumerSecret", Weibo.CONSUMER_SECRET);
    	
    	if (mWeibo == null){
    		mWeibo = OAuthConstant.getInstance().getWeibo();
    	}
    	
    	
    	
        SharedPreferences settings = getSharedPreferences(SETTINGS_TOKEN_PAIR, 0);
        
        mToken = settings.getString(TOKEN, "");
        mTokenSecret = settings.getString(TOKEN_SECRET, "");
        
        settings = getSharedPreferences(WiboMainTabActivity.USER_INFO, 0);
		Utility.mUserName = settings.getString(WiboMainTabActivity.USER_NAME, "defaut");
        
//        Pattern p = Pattern.compile("wibo://WiboMainActivity\\?oauth_token=[a-z0-9]*&oauth_verifier=[0-9]*");//Hello&:/\\?=_, A[a-z0-9]*!
//        
//        Matcher m = p.matcher("wibo://WiboMainActivity?oauth_token=ed7c6a4cdc0da73da1d3200be85b716a&oauth_verifier=365807");//Hello&:/?=_, Andros4d454sd6f2id!
//        boolean b1 = m.matches(); // true
        
        if (mToken.isEmpty() || mTokenSecret.isEmpty()) {
        	requestWindowFeature(Window.FEATURE_NO_TITLE);
            setContentView(R.layout.main);
            mWaitDialog = new ProgressDialog(this);
            
            mWebView = (WebView)findViewById(R.id.webView);
            mWebView.setWebViewClient(new MyWebViewClient());

        	mThread = new Thread(new Runnable() {
				
				@Override
				public void run() {
					try {
						RequestToken requestToken = mWeibo.getOAuthRequestToken("Wibo://WiboMainActivity");
		    			Uri uri = Uri.parse(requestToken.getAuthenticationURL()+ "&from=xweibo");
		    			OAuthConstant.getInstance().setRequestToken(requestToken);
						
		                WebSettings settings = mWebView.getSettings();
		                settings.setJavaScriptEnabled(true);

		                String strUri = uri.getPath();
		                
		                mWebView.loadUrl(requestToken.getAuthenticationURL()+ "&from=xweibo");
		                
//						RequestToken requestToken = mWeibo.getOAuthRequestToken("Wibo://WiboMainActivity");
//		    			Uri uri = Uri.parse(requestToken.getAuthenticationURL()+ "&from=xweibo");
//		    			OAuthConstant.getInstance().setRequestToken(requestToken);
//		    			startActivity(new Intent(Intent.ACTION_VIEW, uri));
					} catch (WeiboException e) {
						e.printStackTrace();
					}
				}
			});
        	mThread.start();
        }else {
        	AccessToken accessToken = new AccessToken(mToken, mTokenSecret);
    		OAuthConstant.getInstance().setAccessToken(accessToken);
            //sendMessage(TURN_TO_MAIN, null);
    		Intent intent = new Intent(WiboMainLoginActivity.this, WiboMainTabActivity.class);
    		intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP );
			startActivity(intent);
            finish();
        }
        
        
    }
    
    public class MyWebViewClient extends WebViewClient {
        //@Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) { 
            view.loadUrl(url); 
            return true; 
        } 

        //@Override 
        public void onPageStarted(WebView view, String url, Bitmap favicon) {  
                Pattern p = Pattern.compile("wibo://WiboMainActivity\\?oauth_token=[a-z0-9]*&oauth_verifier=[0-9]*");//wibo://WiboMainActivity?oauth_token=[a-z0-9]*&oauth_verifier=[0-9]*
                Matcher m = p.matcher(url);
                if (m.matches()) { 
                            //Intent intent = new Intent(WiboMainLoginActivity.this, WiboMainActivity.class);
                            String temp = m.group(0);
                            sendMessage(GET_TOKEN, temp);
                            //intent.putExtra("pin", temp);
                            //startActivity(intent);
                            
                            //finish();
                }
            }
    }
    
    //@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (mWebView.canGoBack()) {
				mWebView.goBack(); // goBack()表示返回webView的上一页面
				return true;
			}
		}
		return super.onKeyDown(keyCode, event);
	}

	/* (non-Javadoc)
	 * @see android.app.Activity#onBackPressed()
	 */
	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		super.onBackPressed();
	}
	
	
}